<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.orgteam_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/ninebasic/org/orgteam";
  import {mapGetters} from "vuex";
  import { validatenull,isvalidatemobile,cardid} from "@/util/validate";
  import {getOrgListByGridId} from "@/api/ninebasic/org/organization";
  export default {
    data() {
      //手机号校验非空
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };  
      //校验身份正号码
      const validateCardid = (rule, value, callback) => {
        if(cardid(value)[0]){
          callback(new Error(cardid(value)[1]))
        }else{
          callback();
        }
      };
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
           height: 'auto',
          calcHeight: 30,
          dialogWidth: 980,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: true,
          dialogClickModal: false,
          column: [
            {
              label: "所属网格",
              prop: "gridId",
              type: "tree",
              span: 24,
              parent: true,
              display: true,
              dicMethod: "get",
              dicUrl: "/api/smart-system/dept/treeByPid",
              props: {
                label: "title"
              
              },
              checkStrictly: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入所属网格",
                trigger: "click"
              }],
            },
            {
              label: "综治机构",
              prop: "orgId",
              type: "select",
              dicData: [],
              hide: true,
              props: {
                  label: "title",
                  value: "key"
                },
              //search: true,
              rules: [{
                required: true,
                message: "请输入综治机构",
                trigger: "blur"
              }],
            },
            {
              label: "综治机构",
              prop: "orgName",
              type: "input",
              search: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "姓名",
              prop: "name",
              type: "input",
              search: true,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }],
            },
             {
              label: "身份证号码",
              prop: "cardNo",
              type: "input",
               rules: [
                {
                  required: true,
                  validator:validateCardid,
                  trigger: 'blur'
                }
              ],
               blur: ({value}) => {
                this.form.birthday  = value.substring(6,10)+"-"+value.substring(10,12)+"-"+value.substring(12,14);
                this.form.sex = value.substring(16,17)%2===0?'2':'1';
              },
            },
            {
              label: "性别",
              prop: "sex",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=sex",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入性别",
                trigger: "blur"
              }],
            },
            {
              label: "民族",
              prop: "nation",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=nation",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入民族",
                trigger: "blur"
              }],
            },
            {
              label: "政治面貌",
              prop: "pearty",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=party",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入政治面貌",
                trigger: "blur"
              }],
            },
            {
              label: "出生日期",
              prop: "birthday",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              hide: true,
              rules: [{
                required: true,
                message: "请输入出生日期",
                trigger: "blur"
              }],
            },
            {
              label: "级别",
              prop: "leavel",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=user_leavel",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入级别",
                trigger: "blur"
              }],
            },
            {
              label: "职务",
              prop: "post",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=sys_user_post",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入职务",
                trigger: "blur"
              }],
            },
            {
              label: "手机号码",
              prop: "phone",
              type: "input",
              rules: [
                {
                  required: true,
                  validator:validatePhone,
                  trigger: 'blur'
                }
              ],
            },
            {
              label: "固定电话",
              prop: "telephone",
              type: "input",
              hide: true,
            },
            {
              label: "学历",
              prop: "education",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=education",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入学历",
                trigger: "blur"
              }],
            },
            {
              label: "特长",
              prop: "specialty",
              type: "checkbox",
              dicUrl: "/api/smart-system/dict/dictionary?code=sys_user_specialty",
              span: 24,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
            },
            {
              label: "备注",
              prop: "textarea",
              type: "input",
              hide: true,
              span: 24
            },
          ]
        },
        data: []
      };
    },
    watch: {
        // 'form.gridId'() {
        //   console.log("0000=="+this.form.gridId);
        //   if(!validatenull(this.form.gridId)){
        //        getOrgListByGridId(this.form.gridId).then(res => {
        //           const column = this.findObject(this.option.column, "orgId");
        //           column.dicData = res.data.data;
        //         });
        //   }
        // },
        'form.gridId': {
             handler(val){
                if(!validatenull(val)){
                  getOrgListByGridId(this.form.gridId).then(res => {
                      const column = this.findObject(this.option.column, "orgId");
                      column.dicData = res.data.data;
                  });
                }
             },
             immediate: true
        },
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.orgteam_add, false),
          viewBtn: this.vaildData(this.permission.orgteam_view, false),
          delBtn: this.vaildData(this.permission.orgteam_delete, false),
          editBtn: this.vaildData(this.permission.orgteam_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        row.specialty = row.specialty.join(",");
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
         row.specialty = row.specialty.join(",");
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        //新增和修改页面，控制网格树加载职能选择末级，查询页面可以选择父级
        if (["edit", "add"].includes(type)) {
            const gridId = this.findObject(this.option.column,"gridId");
            gridId.parent = false;
           
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
             console.log("1="+res.data.data);
              console.log("2="+this.form.specialty.split(","));
             if(this.form.hasOwnProperty("specialty")){
              this.form.specialty = this.form.specialty.split(",");
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 95px ! important;
}
.el-form-item__label {
  width: 95px ! important;
}
</style>
